class LotterySystem {
    constructor() {
        this.drawGroups = []; // 存储每次抽奖的组
        this.fanList = new Map(); // 存储粉丝名单
        this.loadRecords();
        this.loadFanList();
        this.initializeEventListeners();
        this.updateBatchSelector();
        this.updateStats();
    }

    loadRecords() {
        const records = localStorage.getItem('winningRecords');
        if (records) {
            try {
                const data = JSON.parse(records);
                this.drawGroups = data.groups || [];
            } catch (error) {
                console.error('加载记录时出错:', error);
                this.drawGroups = [];
            }
        } else {
            this.drawGroups = [];
        }
        // 如果有记录，默认选择最新的一条
        if (this.drawGroups.length > 0) {
            batchSelect.value = this.drawGroups[0].id;
            //首次加载
            setTimeout(() => {
                this.updateRecordsDisplay(this.drawGroups[0].id);
            }, 50);
        }
    }

    saveRecords() {
        const data = {
            groups: this.drawGroups
        };
        localStorage.setItem('winningRecords', JSON.stringify(data));
    }

    isNumberWon(number) {
        // 检查号码是否已经中奖
        return this.drawGroups.some(group => group.numbers.includes(number));
    }

    updateStats() {
        // 计算已中奖人数
        const totalWinners = this.drawGroups.reduce((sum, group) => sum + group.numbers.length, 0);
        const remainingCount = 10000 - totalWinners;
        
        // 更新显示
        document.getElementById('totalWinners').textContent = totalWinners;
        document.getElementById('remainingCount').textContent = remainingCount;
        
        // 更新当前抽奖数量
        const customCountInput = document.getElementById('customCount');
        const currentCount = parseInt(customCountInput.value) || 10;
        document.getElementById('currentDrawCount').textContent = currentCount;
    }

    async drawNumbers() {
        const customCountInput = document.getElementById('customCount');
        let customCount = parseInt(customCountInput.value) || 10;
        // console.log(customCount)
        // 验证输入值
        if (isNaN(customCount) || customCount < 1 || customCount > 100) {
            return {
                success: false,
                message: '请输入有效的数量（1-100）！'
            };
        }

        const availableNumbers = [];
        for (let i = 1; i <= 10000; i++) {
            if (!this.isNumberWon(i)) {
                availableNumbers.push(i);
            }
        }

        if (availableNumbers.length < customCount) {
            return {
                success: false,
                message: `可用数字不足${customCount}个，无法继续抽奖！`
            };
        }

        // Fisher-Yates 洗牌算法
        for (let i = availableNumbers.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [availableNumbers[i], availableNumbers[j]] = [availableNumbers[j], availableNumbers[i]];
        }

        const selectedNumbers = availableNumbers.slice(0, customCount);
        const currentTime = new Date().toLocaleString();

        // 创建新的抽奖组
        const newGroup = {
            id: Date.now(), // 使用时间戳作为唯一标识
            numbers: selectedNumbers,
            time: currentTime,
            count: customCount // 记录本次抽奖数量
        };

        // 添加新组到组列表
        this.drawGroups.unshift(newGroup);

        this.saveRecords();
        this.updateBatchSelector();
        const recordsList = document.getElementById('recordsList');
        recordsList.innerHTML = '';
        setTimeout(() => {
            this.updateRecordsDisplay(newGroup.id);
        }, 1800);
        this.updateStats();

        return {
            success: true,
            numbers: selectedNumbers,
            message: `抽奖成功！共抽取${customCount}个号码`
        };
    }
    //删除操作
    deleteRecord(number) {
        // 查找包含该号码的所有组
        const groupsWithNumber = this.drawGroups.filter(group => 
            group.numbers.includes(number)
        );

        if (groupsWithNumber.length === 0) {
            return {
                success: false,
                message: `未找到号码 ${number} 的中奖记录！`
            };
        }

        // 从所有组中删除该号码
        this.drawGroups = this.drawGroups.map(group => ({
            ...group,
            numbers: group.numbers.filter(n => n !== number)
        })).filter(group => group.numbers.length > 0);

        this.saveRecords();
        this.updateBatchSelector();
        this.updateRecordsDisplay();
        this.updateStats();
        return {
            success: true,
            message: `成功删除号码 ${number} 的中奖记录！`
        };
    }

    updateBatchSelector() {
        const batchSelect = document.getElementById('batchSelect');
        batchSelect.innerHTML = '<option value="">请选择抽奖批次</option>';
        
        this.drawGroups.forEach(group => {
            const option = document.createElement('option');
            option.value = group.id;
            option.textContent = `抽奖时间: ${group.time}`;
            batchSelect.appendChild(option);
        });

        
    }

    updateRecordsDisplay(batchId = null) {
        const recordsList = document.getElementById('recordsList');
        recordsList.innerHTML = '';

        if (this.drawGroups.length === 0) {
            recordsList.innerHTML = '<div class="record-item">暂无中奖记录</div>';
            return;
        }

        let displayGroup;
        if (batchId) {
            displayGroup = this.drawGroups.find(group => group.id === batchId);
        } else {
            const batchSelect = document.getElementById('batchSelect');
            const selectedId = parseInt(batchSelect.value);
            displayGroup = this.drawGroups.find(group => group.id === selectedId);
        }

        if (!displayGroup) {
            displayGroup = this.drawGroups[0];
        }

        const recordItem = document.createElement('div');
        recordItem.className = 'record-item';
        recordItem.innerHTML = `
            <div>
                <div>抽奖时间: ${displayGroup.time}</div>
                <div>抽奖数量: ${displayGroup.count || displayGroup.numbers.length}</div>
                <div class="winning-numbers">
                    ${displayGroup.numbers.sort((a, b) => a - b)
                        .map(num => {
                            const fanName = this.fanList.get(num.toString()) || '未知粉丝';
                            return `<span class="winning-number">${num}：${fanName}</span>`;
                        })
                        .join('')}
                </div>
            </div>
        `;
     
        recordsList.appendChild(recordItem);
    }

    exportToExcel() {
        const wb = XLSX.utils.book_new();
        
        // 准备数据
        const data = this.drawGroups.map(group => ({
            '抽奖时间': group.time,
            '中奖号码': group.numbers.sort((a, b) => a - b)
                .map(num => `${num} (${this.fanList.get(num.toString()) || '未知粉丝'})`)
                .join(', ')
        }));

        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(data);
        
        // 设置列宽
        const colWidths = [
            { wch: 20 }, // 时间列
            { wch: 100 }  // 号码列（加宽以容纳粉丝名）
        ];
        ws['!cols'] = colWidths;

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "中奖记录");

        // 导出文件
        XLSX.writeFile(wb, `抽奖记录_${new Date().toLocaleDateString()}.xlsx`);
    }

    async showLotteryAnimation(numbers) {
        const animationDiv = document.getElementById('lotteryAnimation');
        const duration = 2000; // 动画持续时间（毫秒）
        const interval = 100; // 更新间隔（毫秒）
        const steps = duration / interval;

        // 获取所有未中奖的号码
        const availableNumbers = [];
        for (let i = 1; i <= 10000; i++) {
            if (!this.isNumberWon(i)) {
                availableNumbers.push(i);
            }
        }

        // 创建动画容器
        animationDiv.innerHTML = `
            <div class="animation-container">
                <div class="rolling-numbers"></div>
                <div class="selected-numbers"></div>
            </div>
        `;

        const rollingNumbersDiv = animationDiv.querySelector('.rolling-numbers');
        const selectedNumbersDiv = animationDiv.querySelector('.selected-numbers');

        // 随机滚动动画
        for (let i = 0; i < steps; i++) {
            // 随机选择一些未中奖的号码显示
            const randomNumbers = Array.from({ length: numbers.length }, () => {
                const randomIndex = Math.floor(Math.random() * availableNumbers.length);
                return availableNumbers[randomIndex];
            });
            
            rollingNumbersDiv.innerHTML = randomNumbers
                .map(num => `<span class="rolling-number">${num}</span>`)
                .join(' ');
            
            await new Promise(resolve => setTimeout(resolve, interval));
        }

        // 显示最终结果
        rollingNumbersDiv.innerHTML = '';
        selectedNumbersDiv.innerHTML = numbers
            .map(num => `<span class="winning-number">${num}</span>`)
            .join(' ');
    }

    initializeEventListeners() {
        const drawButton = document.getElementById('drawButton');
        const clearBtn = document.getElementById('clearBtn');
        const resultSection = document.getElementById('result');
        const exportButton = document.getElementById('exportButton');
        const batchSelect = document.getElementById('batchSelect');
        const customCountInput = document.getElementById('customCount');

        clearBtn.addEventListener('click', async () => { 
            localStorage.clear()
            location.reload()
        })
        drawButton.addEventListener('click', async () => {
            const result =await this.drawNumbers();
            resultSection.innerHTML = '';

            if (result.success) {
                await this.showLotteryAnimation(result.numbers);
                
                const messageDiv = document.createElement('div');
                messageDiv.className = 'success-message';
                messageDiv.textContent = result.message;
                resultSection.appendChild(messageDiv);
            } else {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'error-message';
                messageDiv.textContent = result.message;
                resultSection.appendChild(messageDiv);
            }
        });

        exportButton.addEventListener('click', () => {
            this.exportToExcel();
        });

        batchSelect.addEventListener('change', () => {//切换不同批次抽奖记录
            this.updateRecordsDisplay();
        });

        // 监听自定义数量输入变化
        customCountInput.addEventListener('input', () => {
            this.updateStats();
        });
    }

    async loadFanList() {
        try {
            const response = await fetch('./粉丝名单.xlsx');
            const arrayBuffer = await response.arrayBuffer();
            const workbook = XLSX.read(arrayBuffer, { type: 'array' });
            const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
            const data = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });

            // 将数据存入Map中
            data.forEach(row => {
                if (row[0] && row[1]) {
                    this.fanList.set(row[0].toString(), row[1]);
                }
            });
        } catch (error) {
            console.error('加载粉丝名单失败:', error);
        }
    }
}

// 初始化抽奖系统
document.addEventListener('DOMContentLoaded', () => {
    new LotterySystem();
}); 